import Field from './field';
import Validator from './../core/validate';
import {
    getKeyboardDir,
} from './../utils';
import {
    createTemplateSelectLi,
} from './../core/template';
/**
 * 下拉框字段类
 */
export default class SelectField extends Field {
    constructor(options) {
        super(options);
        this.list = options.items;
        this.items = options.items || [];
        this.disabled = options.disabled;
        this.selectName = options.selectName || 'name';
        this.selectValue = options.selectValue || 'id';
        this.placeholder = options.placeholder || '请选择';
        this.filterable = options.filterable;
        this.listVisible = options.listVisible;
        this.shieldKeys = ['top', 'bottom', 'ok'];
        this.listCount = -1;
        this.name = '';
        this.setName();
        if (options.validate) this.validate = new Validator(this, options);
    }
    // 设置name
    setName() {
        const { items, value, selectName, selectValue } = this;
        items.forEach(item => {
            if (value != '' && value == item[selectValue]) {
                this.name = item[selectName];
            }
        });
    }
    // 事件绑定
    bindEvent() {
        // 监听box下input
        this.inputEl = this.$el.children('input').get(0);
        this.keyupHandle = (e) => this.keyupProcessing(e);
        this.filterable && this.inputEl.addEventListener('keyup', this.keyupHandle);
        // 监听box
        this.selectEl = this.$el.get(0);
        this.mouseenterHandle = (e) => {
            if (this.disabled) return;
            this.value && this.$el.children('div').addClass('clear').removeClass('triangle')
        };
        this.mouseleaveHandle = (e) => this.value && this.$el.children('div').addClass('triangle').removeClass('clear');
        this.selectEl.addEventListener('mouseenter', this.mouseenterHandle);
        this.selectEl.addEventListener('mouseleave', this.mouseleaveHandle);
    }
    // 解除事件
    removeEvent() {
        this.selectEl.removeEventListener('mouseenter', this.mouseenterHandle);
        this.selectEl.removeEventListener('mouseleave', this.mouseleaveHandle);
        this.filterable && this.inputEl.removeEventListener('keyup', this.keyupHandle);
    }
    // 事件处理
    eventProcessing(type, element) {
        this[type + 'Processing'](element);
    }
    // 清除处理
    clearProcessing(element) {
        this.checkProcessing(element);
        this.$el.children('div').addClass('triangle').removeClass('clear');
    }
    // 点击处理
    clickProcessing() {
        console.log('clickProcessing');
        if (this.disabled) return;
        this.detectionSelectBox();
        const prevSelect = this.table.currentSelect;
        const $selectBox = this.table.$selectBox;
        const inputValue = this.inputEl.value.trim();
        if (prevSelect === this) {
            this.listVisible = !this.listVisible;
        } else {
            if (prevSelect) {
                const prevInputValue = prevSelect.inputEl.value.trim();
                if (prevInputValue != prevSelect.name) {
                    prevSelect.inputEl.value = prevSelect.name;
                }
                prevSelect.$el.removeClass('active');
            }
            this.listVisible = true;
        }
        if (this.listVisible) {
            const { left: boxLeft, top: boxTop } = this.table.$container.offset();
            const { left, top, height } = this.$el.offset();
            const tableBodyEl = this.table.$tableBody.get(0);
            const { scrollLeft, scrollTop } = tableBodyEl;
            const leftValue = left - boxLeft;
            const topValue = top - boxTop + height;
            this.table.selectPoint.left = leftValue;
            this.table.selectPoint.top = topValue;
            this.table.selectPoint.curScrollLeft = scrollLeft;
            this.table.selectPoint.curScrollTop = scrollTop;
            $selectBox.show().css({ left: leftValue, top: topValue });
            if (this.filterable) {
                this.inputEl.removeAttribute('readonly');
                if (inputValue) {
                    this.list = this.items.filter(item => item[this.selectName].indexOf(inputValue) >= 0);
                } else {
                    this.list = this.items;
                }
            } else {
                this.list = this.items;
            }
            this.$el.addClass('active');
        } else {
            this.closeSelectList();
        }
        let lis = '';
        this.list.forEach(item => {
            lis += createTemplateSelectLi(item[this.selectValue], item[this.selectName]);
        })
        $selectBox.find('ul').html(lis);
        this.table.currentSelect = this;
    }
    // 按键处理
    keyupProcessing(event) {
        const direction = getKeyboardDir(event);
        if (!this.listVisible || this.shieldKeys.indexOf(direction) >= 0) return;
        const name = event.target.value.trim();
        const { value: oldValue, selectName, selectValue } = this;
        if (oldValue || name.length > 0) {
            this.list = this.items.filter(item => item[selectName].indexOf(name) >= 0);
        } else {
            this.list = this.items;
        }
        let lis = '';
        this.list.forEach(item => {
            lis += createTemplateSelectLi(item[selectValue], item[selectName]);
        })
        this.table.$selectBox.find('ul').html(lis);
    }
    // 选中处理
    checkProcessing(element) {
        const { rowIndex, prop, value: oldValue } = this;
        const newValue = element.getAttribute('value') || '';
        const inputValue = element.innerText;
        // 实例值更新
        this.value = newValue;
        // 实例名更新
        this.name = inputValue;
        // 数据更新
        this.table.data[rowIndex][prop] = newValue;
        // dom值更新
        this.inputEl.value = inputValue;
        // dom属性更新
        this.inputEl.setAttribute('placeholder', inputValue || this.placeholder);
        // 关闭下拉
        this.closeSelectList();
        // 触发选择后验证
        this.validate && this.validate.verification(newValue).catch(() => { });
        // 触发全局事件钩子
        this.table.event.onFieldChange(rowIndex, prop, oldValue, newValue);
    }
    // 设置单项数据
    setSpecifiedItem(newValue) {
        const { rowIndex, prop, selectValue, selectName } = this;
        this.items.forEach(item => {
            if (item[selectValue] == newValue) {
                const inputValue = item[selectName];
                this.value = newValue;
                this.name = inputValue;
                this.inputEl.value = inputValue;
                this.inputEl.setAttribute('placeholder', inputValue || this.placeholder);
                this.table.data[rowIndex][prop] = newValue;
            }
        });
    }
    // 关闭下拉列表
    closeSelectList() {
        this.list = [];
        this.listCount = -1;
        this.listVisible = false;
        this.$el.removeClass('active');
        this.table.$selectBox && this.table.$selectBox.hide().find('ul').html('');
        this.inputEl.setAttribute('readonly', 'readonly');
        this.inputEl.blur();
        return this;
    }
    // 恢复输入框值
    recoverSelectName() {
        this.inputEl.value = this.name;
    }
    // 生成验证
    generateValidateWarn(message) {
        const spanEl = this.$el.children('span').get(0);
        spanEl.innerText = message;
        message ? $(this.inputEl).addClass('border') : $(this.inputEl).removeClass('border');
    }
}